<template>
  <div class="task-detail-container">
    <div class="task-detail">
      <!-- 返回按钮 -->
      <div class="back-button" @click="goBack">
        <i class="fas fa-arrow-left"></i>
        <span>返回小组任务</span>
      </div>

      <!-- 任务详情 -->
      <div v-if="loading.task" class="loading-container">
        <div class="loading-spinner"></div>
        <p>加载中...</p>
      </div>
      <div v-else-if="task" class="task-content">
        <div class="task-header">
          <h1>{{ task.title }}</h1>
          <div class="task-meta">
            <span class="task-status" :class="task.status">{{ getStatusText(task.status) }}</span>
            <span class="task-deadline"><i class="far fa-clock"></i> 截止日期: {{ formatDate(task.deadline) }}</span>
            <span class="task-creator"><i class="far fa-user"></i> 创建人: {{ task.creator_name || '未知' }}</span>
          </div>
        </div>
        
        <div class="task-description">
          <h2>任务描述</h2>
          <div class="description-content">{{ task.description }}</div>
        </div>
        
        <!-- 我的任务状态（如果分配给当前用户） -->
        <div v-if="myAssignment" class="my-assignment">
          <h2>我的任务</h2>
          <div class="assignment-status">
            <div class="status-label">状态:</div>
            <div :class="['status-value', myAssignment.completed ? 'completed' : 'ongoing']">
              {{ myAssignment.completed ? '已完成' : '进行中' }}
            </div>
            <button 
              v-if="!myAssignment.completed" 
              class="mark-completed-btn" 
              @click="markTaskCompleted"
            >
              标记为已完成
            </button>
          </div>
        </div>
        
        <!-- 任务提交部分（如果分配给当前用户并且未完成） -->
        <div v-if="myAssignment && !myAssignment.completed" class="task-submission-form">
          <h2>提交任务</h2>
          <div class="form-group">
            <label>内容</label>
            <textarea 
              v-model="submissionForm.content" 
              placeholder="请输入任务完成情况说明..."
              rows="4"
            ></textarea>
          </div>
          
          <div class="form-group">
            <label>附件图片</label>
            <div class="image-upload">
              <input 
                type="file" 
                ref="fileInput" 
                accept="image/*" 
                @change="handleImageSelected"
                style="display: none"
              >
              <button class="upload-btn" @click="triggerFileInput">
                <i class="fas fa-upload"></i> 上传图片
              </button>
              <span v-if="submissionForm.imageFile" class="file-name">
                {{ submissionForm.imageFile.name }}
              </span>
            </div>
            <div v-if="submissionForm.imagePreview" class="image-preview">
              <img :src="submissionForm.imagePreview" alt="预览图">
            </div>
          </div>
          
          <div class="form-actions">
            <button 
              class="submit-btn" 
              @click="submitTask" 
              :disabled="isSubmitting"
            >
              {{ isSubmitting ? '提交中...' : '提交任务' }}
            </button>
          </div>
        </div>
        
        <!-- 任务提交历史 -->
        <div v-if="mySubmission" class="submission-history">
          <h2>我的提交</h2>
          <div class="submission-item">
            <div class="submission-meta">
              <div class="submission-time">提交时间: {{ formatDateTime(mySubmission.submit_time) }}</div>
              <div :class="['submission-status', mySubmission.review_status]">
                状态: {{ getReviewStatusText(mySubmission.review_status) }}
              </div>
            </div>
            <div class="submission-content">{{ mySubmission.content }}</div>
            <div v-if="mySubmission.image_url" class="submission-image">
              <img :src="mySubmission.image_url" alt="提交图片">
            </div>
            <div v-if="mySubmission.review_comment" class="review-comment">
              <h3>审核意见</h3>
              <div class="comment-content">{{ mySubmission.review_comment }}</div>
            </div>
          </div>
        </div>
        
        <!-- 管理员查看所有提交（仅小组管理员可见） -->
        <div v-if="isAdmin" class="all-submissions">
          <h2>所有提交</h2>
          <div v-if="loading.submissions" class="loading-container">
            <div class="loading-spinner"></div>
            <p>加载提交数据中...</p>
          </div>
          <div v-else-if="submissions.length === 0" class="empty-state">
            <i class="fas fa-inbox"></i>
            <p>暂无提交</p>
          </div>
          <div v-else class="submission-list">
            <div v-for="submission in submissions" :key="submission.id" class="submission-item">
              <div class="submission-header">
                <div class="submitter-info">
                  <span class="submitter-name">{{ submission.username }}</span>
                  <span class="submission-time">{{ formatDateTime(submission.submit_time) }}</span>
                </div>
                <div :class="['submission-status', submission.review_status]">
                  {{ getReviewStatusText(submission.review_status) }}
                </div>
              </div>
              <div class="submission-content">{{ submission.content }}</div>
              <div v-if="submission.image_url" class="submission-image">
                <img :src="submission.image_url" alt="提交图片">
              </div>
              <div v-if="submission.review_comment" class="review-comment">
                <h4>审核意见</h4>
                <div class="comment-content">{{ submission.review_comment }}</div>
              </div>
              
              <!-- 审核表单（如果未审核） -->
              <div v-if="submission.review_status === 'pending'" class="review-form">
                <h4>审核</h4>
                <div class="form-group">
                  <label>审核意见</label>
                  <textarea 
                    v-model="reviewForms[submission.id]" 
                    placeholder="请输入审核意见..."
                    rows="2"
                  ></textarea>
                </div>
                <div class="review-actions">
                  <button 
                    class="approve-btn" 
                    @click="reviewSubmission(submission.id, 'approved', reviewForms[submission.id])"
                  >
                    <i class="fas fa-check"></i> 通过
                  </button>
                  <button 
                    class="reject-btn" 
                    @click="reviewSubmission(submission.id, 'rejected', reviewForms[submission.id])"
                  >
                    <i class="fas fa-times"></i> 驳回
                  </button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { taskApi } from '@/utils/api'

export default {
  name: 'TaskDetailView',
  data() {
    return {
      taskId: null,
      groupId: null,
      userId: parseInt(localStorage.getItem('userId')),
      isAdmin: false,
      task: null,
      myAssignment: null,
      submissions: [],
      mySubmission: null,
      loading: {
        task: true,
        submissions: false
      },
      submissionForm: {
        content: '',
        imageFile: null,
        imagePreview: null
      },
      reviewForms: {},
      isSubmitting: false
    }
  },
  mounted() {
    // 从路由参数获取任务ID
    this.taskId = this.$route.params.id
    console.log('任务ID:', this.taskId)
    
    if (this.taskId) {
      this.fetchTaskData()
      // 在获取任务基本信息后执行
      this.fetchTaskSubmissions()
    }
  },
  methods: {
    calculateTaskStatus(task) {
      if (!task) return 'ongoing';
      
      // 检查是否过期
      const now = new Date();
      const deadline = new Date(task.deadline);
      if (deadline < now) {
        return 'expired';
      }
      
      // 使用任务的原始状态
      return task.status || 'ongoing';
    },
    goBack() {
      this.$router.push(`/group/${this.groupId}`)
    },
    async fetchTaskData() {
      this.loading.task = true;
      try {
        console.log("开始获取任务详情数据，任务ID:", this.taskId);
        const response = await taskApi.getTaskDetail(this.taskId);
        console.log("任务详情API响应:", response);
        
        if (response.result === 'success' && response.tasks && response.tasks.length > 0) {
          // 处理任务数据 - 注意检查返回数据结构
          const taskData = response.tasks[0]; // 获取第一个任务对象
          console.log("处理后的任务数据:", taskData);
          
          this.task = {
            ...taskData,
            status: this.calculateTaskStatus(taskData)
          };
          
          // 获取任务创建者名称（如果后端未返回）
          if (!this.task.creator_name && this.task.creator_id) {
            console.log("创建者名称为空，尝试单独获取，创建者ID:", this.task.creator_id);
            
            try {
              const userInfoResponse = await fetch(`${baseURL}/user/getUserInfos?user_id=${this.task.creator_id}&token=${localStorage.getItem('token')}`);
              const userData = await userInfoResponse.json();
              console.log("用户信息API响应:", userData);
              
              if (userData.result === 'success') {
                this.task.creator_name = userData.userInfos.user_name;
                console.log("成功获取创建者名称:", this.task.creator_name);
              }
            } catch (error) {
              console.error("获取创建者名称失败:", error);
            }
          }
          
          // 查找当前用户的任务分配
          if (taskData.assignments) {
            console.log("查找当前用户的任务分配，用户ID:", this.userId);
            this.myAssignment = taskData.assignments.find(a => Number(a.user_id) === Number(this.userId));
            console.log("当前用户的任务分配情况:", this.myAssignment);
          }
          
          // 设置小组ID（如果需要）
          if (taskData.group_id && !this.groupId) {
            this.groupId = taskData.group_id;
            console.log("设置小组ID:", this.groupId);
          }
          
          console.log('最终任务数据:', this.task);
        } else {
          console.error("获取任务详情失败:", response.message);
          this.showError('获取任务详情失败: ' + (response.message || '未知错误'));
        }
      } catch (error) {
        console.error('获取任务详情出错:', error);
        this.showError('获取任务详情出错: ' + (error.message || '未知错误'));
      } finally {
        this.loading.task = false;
      }
    },
    async fetchTaskSubmissions() {
      if (!this.taskId) return;
      
      this.loading.submissions = true;
      try {
        const response = await taskApi.getTaskSubmissions(this.taskId);
        if (response.result === 'success') {
          this.submissions = response.submissions || [];
          
          // 找到当前用户的提交
          if (this.submissions.length > 0) {
            this.mySubmission = this.submissions.find(s => s.user_id === this.userId);
          }
        } else {
          console.error('获取任务提交失败:', response.message);
        }
      } catch (error) {
        console.error('获取任务提交出错:', error);
      } finally {
        this.loading.submissions = false;
      }
    },
    async markTaskCompleted() {
      try {
        console.log("开始标记任务完成，任务ID:", this.taskId, "用户ID:", this.userId);
        
        if (!this.taskId) {
          console.error("标记任务失败: 缺少任务ID");
          this.showError('标记任务失败: 缺少任务ID');
          return;
        }
        
        if (!this.userId) {
          console.error("标记任务失败: 缺少用户ID");
          this.showError('标记任务失败: 缺少用户ID');
          return;
        }
        
        const response = await taskApi.completeTask(this.taskId, this.userId);
        console.log("标记任务完成响应:", response);
        
        if (response.result === 'success') {
          this.myAssignment.completed = true;
          this.showSuccess('任务已标记为完成');
          
          // 刷新任务数据以获取最新状态
          await this.fetchTaskData();
        } else {
          console.error("标记任务完成失败:", response.message);
          this.showError('标记任务完成失败: ' + response.message);
        }
      } catch (error) {
        console.error('标记任务完成错误:', error);
        this.showError('标记任务完成失败，请稍后重试');
      }
    },
    triggerFileInput() {
      this.$refs.fileInput.click()
    },
    handleImageSelected(event) {
      const file = event.target.files[0]
      if (!file) return
      
      // 检查文件大小（限制为5MB）
      if (file.size > 5 * 1024 * 1024) {
        this.showError('图片大小不能超过5MB')
        return
      }
      
      // 检查文件类型
      if (!file.type.startsWith('image/')) {
        this.showError('请选择图片文件')
        return
      }
      
      this.submissionForm.imageFile = file
      
      // 创建预览
      const reader = new FileReader()
      reader.onload = e => {
        this.submissionForm.imagePreview = e.target.result
      }
      reader.readAsDataURL(file)
    },
    async submitTask() {
      // 表单验证
      if (!this.submissionForm.content.trim()) {
        this.showError('请输入任务完成说明')
        return
      }
      
      this.isSubmitting = true
      
      try {
        const formData = new FormData()
        formData.append('assignment_id', this.myAssignment.id)
        formData.append('content', this.submissionForm.content)
        
        if (this.submissionForm.imageFile) {
          formData.append('image', this.submissionForm.imageFile)
        }
        
        const response = await taskApi.submitTask(formData)
        
        if (response.result === 'success') {
          this.showSuccess('任务提交成功')
          this.submissionForm.content = ''
          this.submissionForm.imageFile = null
          this.submissionForm.imagePreview = null
          
          // 重新获取提交信息
          this.fetchTaskSubmissions()
        } else {
          this.showError('任务提交失败: ' + response.message)
        }
      } catch (error) {
        console.error('提交任务错误:', error)
        this.showError('提交任务失败，请稍后重试')
      } finally {
        this.isSubmitting = false
      }
    },
    async reviewSubmission(submissionId, status, comment) {
      // 验证审核意见
      if (!comment.trim()) {
        this.showError('请输入审核意见')
        return
      }
      
      try {
        const response = await taskApi.reviewSubmission(submissionId, status, comment)
        
        if (response.result === 'success') {
          this.showSuccess('审核成功')
          
          // 更新本地状态
          const submission = this.submissions.find(s => s.id === submissionId)
          if (submission) {
            submission.review_status = status
            submission.review_comment = comment
          }
          
          // 清空审核表单
          this.$set(this.reviewForms, submissionId, '')
        } else {
          this.showError('审核失败: ' + response.message)
        }
      } catch (error) {
        console.error('审核任务错误:', error)
        this.showError('审核失败，请稍后重试')
      }
    },
    formatDate(dateString) {
      if (!dateString) return '未设置'
      const date = new Date(dateString)
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`
    },
    formatDateTime(dateString) {
      if (!dateString) return '未知'
      const date = new Date(dateString)
      return `${this.formatDate(dateString)} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
    },
    getStatusText(status) {
      const statusMap = {
        ongoing: '进行中',
        completed: '已完成',
        expired: '已过期'
      }
      return statusMap[status] || status
    },
    getReviewStatusText(status) {
      const statusMap = {
        pending: '待审核',
        approved: '已通过',
        rejected: '已驳回'
      }
      return statusMap[status] || status
    },
    showSuccess(message) {
      // 这里使用你的项目中的提示组件或方法
      alert(message) // 临时使用alert
    },
    showError(message) {
      // 这里使用你的项目中的提示组件或方法
      alert(message) // 临时使用alert
    }
  },
  created() {
    this.groupId = parseInt(this.$route.query.groupId)
    
    // 检查是否是管理员
    // 通过URL参数传递或从localStorage获取
    this.isAdmin = this.$route.query.isAdmin === 'true' || localStorage.getItem('isGroupAdmin') === 'true'
  }
}
</script>

<style scoped>
.task-detail-container {
  min-height: 100vh;
  background: #f0f7ff;
  padding: 20px;
}

.task-detail {
  max-width: 1000px;
  margin: 0 auto;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

.back-button {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: #f1f5f9;
  border-radius: 6px;
  margin-bottom: 24px;
  cursor: pointer;
  transition: all 0.2s;
}

.back-button:hover {
  background: #e2e8f0;
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 40px;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #e2e8f0;
  border-top-color: #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  to { transform: rotate(360deg); }
}

.task-header {
  margin-bottom: 24px;
}

.task-header h1 {
  margin-bottom: 12px;
  color: #2c3e50;
}

.task-meta {
  display: flex;
  flex-wrap: wrap;
  gap: 16px;
  font-size: 14px;
  color: #64748b;
}

.task-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.task-status.ongoing {
  background: #ecfdf5;
  color: #047857;
}

.task-status.completed {
  background: #f0f9ff;
  color: #0369a1;
}

.task-status.expired {
  background: #fef2f2;
  color: #b91c1c;
}

.task-description {
  margin-bottom: 30px;
}

.task-description h2 {
  font-size: 1.25rem;
  margin-bottom: 12px;
  color: #334155;
}

.description-content {
  white-space: pre-wrap;
  line-height: 1.6;
}

.my-assignment {
  margin-bottom: 30px;
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
}

.my-assignment h2 {
  font-size: 1.25rem;
  margin-bottom: 12px;
  color: #334155;
}

.assignment-status {
  display: flex;
  align-items: center;
  gap: 12px;
}

.status-label {
  font-weight: 500;
}

.status-value {
  padding: 4px 8px;
  border-radius: 4px;
}

.status-value.ongoing {
  background: #ecfdf5;
  color: #047857;
}

.status-value.completed {
  background: #f0f9ff;
  color: #0369a1;
}

.mark-completed-btn {
  margin-left: auto;
  padding: 6px 12px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.mark-completed-btn:hover {
  background: #2980b9;
}

.task-submission-form {
  margin-bottom: 30px;
  padding: 20px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.task-submission-form h2 {
  font-size: 1.25rem;
  margin-bottom: 16px;
  color: #334155;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #334155;
}

.form-group textarea {
  width: 100%;
  padding: 10px;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  resize: vertical;
}

.image-upload {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 12px;
}

.upload-btn {
  padding: 8px 16px;
  background: #f1f5f9;
  border: 1px solid #e2e8f0;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.upload-btn:hover {
  background: #e2e8f0;
}

.file-name {
  color: #64748b;
}

.image-preview {
  margin-top: 12px;
  max-width: 300px;
}

.image-preview img {
  width: 100%;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
}

.submit-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-btn:hover {
  background: #2980b9;
}

.submit-btn:disabled {
  background: #94a3b8;
  cursor: not-allowed;
}

.submission-history,
.all-submissions {
  margin-top: 30px;
}

.submission-history h2,
.all-submissions h2 {
  font-size: 1.25rem;
  margin-bottom: 16px;
  color: #334155;
}

.submission-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.submission-item {
  padding: 16px;
  background: #f8fafc;
  border-radius: 8px;
  border: 1px solid #e2e8f0;
}

.submission-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 12px;
}

.submitter-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.submitter-name {
  font-weight: 500;
  color: #334155;
}

.submission-time {
  font-size: 12px;
  color: #64748b;
}

.submission-status {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.submission-status.pending {
  background: #fffbeb;
  color: #b45309;
}

.submission-status.approved {
  background: #ecfdf5;
  color: #047857;
}

.submission-status.rejected {
  background: #fef2f2;
  color: #b91c1c;
}

.submission-content {
  margin-bottom: 12px;
  white-space: pre-wrap;
  line-height: 1.6;
}

.submission-image {
  margin-bottom: 12px;
}

.submission-image img {
  max-width: 100%;
  max-height: 300px;
  border-radius: 6px;
  border: 1px solid #e2e8f0;
}

.review-comment {
  margin-top: 16px;
  padding: 12px;
  background: #f1f5f9;
  border-radius: 6px;
}

.review-comment h3,
.review-comment h4 {
  margin-bottom: 8px;
  font-size: 1rem;
  color: #334155;
}

.comment-content {
  color: #475569;
  white-space: pre-wrap;
}

.review-form {
  margin-top: 16px;
  padding: 12px;
  background: #f1f5f9;
  border-radius: 6px;
}

.review-actions {
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.approve-btn,
.reject-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.2s;
}

.approve-btn {
  background: #10b981;
  color: white;
}

.approve-btn:hover {
  background: #059669;
}

.reject-btn {
  background: #ef4444;
  color: white;
}

.reject-btn:hover {
  background: #dc2626;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 40px;
  color: #94a3b8;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
}
</style> 